import { createSSRApp } from 'vue'
import { qszrUI } from '@/components/qszr-core/packages/components'
import uView from './uni_modules/vk-uview-ui'
import { getPlugin } from '@/libs/sysConfig'
import { StompStarter } from '@/hooks/stomp/StompStarter'
import { getCdnUrl } from '@/utils'
import store from '@/store/global'
import App from './App.vue'
import { useUserStore } from './store/modules/user'
import { useAmapKeyStore } from './store/modules/amapKey'
import { doGetAmapKey, getLocation, locToAddress } from './apis/amap'

const amapKeyStore = useAmapKeyStore(store)
doGetAmapKey().then(async (res) => {
  console.log(res)
  if (res.data) {
    amapKeyStore.SET_ALL_KEY(res.data)
    const lb = await getLocation()
    locToAddress(lb)
  }
})
const $userStore = useUserStore(store)
/**
 * navigateTo拦截器，只针对微信小程序端生效
 */
const navigateToInterceptor = () => {
  // #ifdef MP-WEIXIN
  const originalNavigateTo = uni.navigateTo.bind(uni)
  uni.navigateTo = (options) => {
    // eslint-disable-next-line no-undef
    const pages = getCurrentPages()
    if (pages.length > 7) {
      uni.redirectTo(options)
    } else {
      originalNavigateTo(options)
    }
  }
  // #endif
}
/**
 * navigateBack拦截器，只针对H5生效
 */
const navigateBackInterceptor = () => {
  // #ifdef H5
  window.addEventListener('popstate', (event) => {
    // 当页面前进或者后退时，
    $userStore.CLEAR_NEED_AUTH()
  })
  uni.navigateBack = (options) => {
    const backHistory = options?.delta || 1
    history.go(-backHistory)
  }
  // #endif
}
// global.WebSocket = window.WebSocket = WebSocketPolyfill
export function createApp() {
  // uni.$popup = new Popup()
  navigateToInterceptor()
  navigateBackInterceptor()
  const app = createSSRApp(App)
  app.config.globalProperties.$getCdnUrl = getCdnUrl
  app.use(store).use(qszrUI).use(uView)
  getPlugin()
  StompStarter.start()
  return {
    app,
  }
}
